$(function() {
	department = new Department();
	layui.use('layer', function() {
		var layer = layui.layer;
	});
	department.init();
	formUrl = department.formUrl;
//	$("#import")
//			.on(
//					"click",
//					function() {
//						var me = this;
//						layer
//								.open({
//									type : 1,
//									title : "请导入Excel",
//									fix : false,
//									shade : 0.4,
//									shadeClose : false,
//									maxmin : false,
//									zIndex : layer.zIndex,
//									area : [ '250px', '180px' ],
//									content : '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input id="file" type="file" style="display: none" onchange="$(\'#name\').val(this.files[0].name);"> <input id="name" class="input-large" type="text" style="height: 30px; width:auto"><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a class="btn"  onclick="$(\'input[id=file]\').click();">选择文件</a><a class="btn" href=downLoad.htm>模板下载</a>',
//									btn : [ '导入', '取消' ],
//									yes : function(index, layro) {
//										var fileObj = document.getElementById("file").files[0];
//										var zzbm = $("#zzbm").val();
//										if (!fileObj) {
//											layer.attr("请选择文件");
//										} else {
//											var filename = fileObj.name;
//											var ex = filename.lastIndexOf(".");
//											var suffix = filename.substring(ex).toLowerCase();
//											if (filename == "" || !(".xlsx" == suffix || ".xls" == suffix)) {
//												layer.alert("文件格式不对，请选择xls或xlsx格式！");
//											} else {
//												var formFile = new FormData();
//												var zzbm = $("#zzbm").val();
//												formFile.append("file", fileObj); // 加入文件对象
//												formFile.append("zzbm", zzbm);
//												var data = formFile;
//												$.ajax({
//													url : __ctx + "/card/department/department/upload.htm",
//													data : data,
//													type : "post",
//													dataType : "json",
//													cache : false, // 上传文件无需缓存
//													processData : false, // 用于对data参数进行序列化处理
//																			// 这里必须false
//													contentType : false, // 必须
//													beforeSend : function() {
//														// 禁用按钮防止重复提交
//														$("a.layui-layer-btn0").css("pointer-events", "none");
//														$("a.layui-layer-btn1").css("pointer-events", "none");
//													},
//													success : function(data) {
//														DialogUtil.confirm(data.message);
//														layer.close(index);
//													}
//												});
//											}
//										}
//									}
//								});
//					});
	$("#import").click(function(){
		DialogUtil.dialog({
			title : "导入",
			content : __ctx + '/rdp/card/department/department/importList.htm',
			area : [ '80%', '80%' ],
			btn : [ {
				label : '关闭',
				iconCls : 'btn btn-danger fa fa-cancel',
				action : function(dialog, index) {
					DialogUtil.close(index);
				}
			} ],
			end : function() {
				//$("#refoundDetailGrid").trigger("reloadGrid");
			}
		});
	})
	
});

(function() {
	// 定义常量
	var _consts = {
		TREE_ID : 'departmentTree',// 树
		TREE : '#departmentTree', // 树ID
		FORM : '#departmentForm',// 表单form
		FORMGET : '#departmentFormGet',// 表单form
		PACKURL : __ctx + '/rdp/card/department/department',// 包路径

	};
	Department = function() {
		// 定义属性
	};

	Department.prototype = {
		consts : _consts,
		init : function() {
			if (this.hasInit) // 是否已初始化
				return false;
			this.hasInit = true;
			if ($(this.consts.TREE).length > 0) {
				this._initDepartmentTree();
			}
			if ($(this.consts.FORM).length > 0) {// 表单
				this._initForm();
				this._initData();
				this._initOffice('e');
			}
			if ($(this.consts.FORMGET).length > 0) {// 明细页面office控件初始化
				this._initOffice('r');
			}
		},
		_initOffice : function(_rights) {
		},

		_initDepartmentTree : function() {
			var me = this;
			// 初始化布局
			var layout = $('body').layout({
				applyDefaultStyles : true
			});
			layout.addPinBtn(".pinBtn", "west");
			// 树
			this._treeFrameResize();
			// 缩放时候计算高度
			$(window).resize(function() {
				me._treeFrameResize();
			});
			this.loadTree();
			// 初始化滚动
			this.initLeftScroll();
			// 初始化树的顶部按钮
			this.initTreeToolbar();
		},
		/**
		 * 缩放时候计算高度
		 */
		_treeFrameResize : function() {
			$('.treeFrame').height($(window).height() - 20);
			$(this.consts.TREE).height($(window).height() - 130);
		},
		// 加载树
		loadTree : function() {
			var me = this;
			this._treeRootId = 0;
			this.expandByDepth = 1;
			var setting = {
				async : {
					enable : false
				},
				data : {
					key : {
						name : "orgname"
					},
					simpleData : {
						enable : true,
						idKey : "orgcode",
						pIdKey : "parentcode",
						rootPId : "0",
						id : "id",
					}
				},
				callback : {
					onClick : function(e, treeId, treeNode) {
						me.treeOnLeftClick(me, treeNode);
					},
					onRightClick : function(e, treeId, treeNode) {
						me.treeOnRightClick(me, treeNode, e);
					},
					beforeDrop : null,
					onDrop : null
				}
			};
			var url = _consts.PACKURL + "/getTreeData.htm";
			$.post(url, function(result) {
				me.departmentTree = $.fn.zTree.init($(me.consts.TREE), setting, result);
				if (me.expandByDepth != 0) {
					var nodes = me.departmentTree.getNodesByFilter(function(node) {
						return (node.level == me.expandByDepth);
					});
					if (nodes.length > 0) {
						for (var idx = 0; idx < nodes.length; idx++) {
							me.departmentTree.expandNode(nodes[idx], true, false);
						}
					}
				} else {
					me.departmentTree.expandAll(true);
				}
			});
		},
		/**
		 * 重新加载树
		 */
		reFresh : function() {
			// 刷新左边的树
			this.loadTree();
		},
		treeOnLeftClick : function(me, treeNode) {
			me.selectTreeNode = treeNode;
			var nodeId = treeNode.id;
			if ($.isEmpty(nodeId))
				nodeId = 0;
			var url = _consts.PACKURL + "/get.htm?id=" + nodeId;
			$("#listFrame").attr("src", url);
		},
		treeOnRightClick : function(me, treeNode, e) {
			if (!treeNode)
				return;
			this.departmentTree.selectNode(treeNode);

			// 获取当前点击左树的参与者Id
			var nodeId = treeNode.orgcode;
			var menu = null;
			// /特殊节点能新增
			if (nodeId == '' || nodeId == undefined || nodeId == "0") {
				menu = $('#rootMenu');
			} else {
				menu = $('#groupMenu');
			}
			menu.contextMenu(e, {
				onItem : function(context, ev) {
					var target = $(ev.target), action = target.data("action");
					if (target.hasClass('disabled'))
						return false;
					switch (action) {
					case "node_add":// 增加节点
						me.addNode(treeNode);
						break;
					case "node_edit":// 编辑节点
						me.editNode(treeNode);
						break;
					case "node_del":// 删除节点
						me.delNode(treeNode);
						break;
					}
				}
			});
		},
		delNode : function(node) {
			if (node.children != null && node.children.length > 0) {
				DialogUtil.toastr("请先删除子节点！");
				return;
			}
			var me = this;
			var url = _consts.PACKURL + "/remove.htm", me = this;
			DialogUtil.confirm('确认删除吗？', function(rtn) {
				if (!rtn)
					return;
				$.ajax({
					type : "POST",
					url : url,
					data : {
						id : node.id
					},
					success : function(responseText) {
						var resultMessage = new com.lc.form.ResultMessage(responseText);
						if (resultMessage.isSuccess()) {
							me.reFresh();
							DialogUtil.toastr(resultMessage.getMessage(), true);
						} else {
							DialogUtil.error(resultMessage.getMessage());
						}
					},
					errror : function(error) {
						DialogUtil.error(error);
					}
				});
			});
		},
		addNode : function(node) {
			var url = _consts.PACKURL + "/edit.htm?parentcode=" + node.orgcode;
			$("#listFrame").attr("src", url);
		},
		editNode : function(node) {
			var url = _consts.PACKURL + "/edit.htm?id=" + node.id;
			$("#listFrame").attr("src", url);
		},
		/**
		 * 左侧菜单的滚动
		 */
		initLeftScroll : function() {
			$(_consts.TREE).niceScroll({
				horizrailenabled : false,
				cursorborder : "0",
				cursorwidth : "6px",
				cursorcolor : "#2A2A2A",
				zindex : "5555",
				autohidemode : true,
				bouncescroll : true,
				mousescrollstep : '40',
				scrollspeed : '100',
				background : "#999",
				cursoropacitymax : "0.6",
				cursorborderradius : "0"
			});
			$(_consts.TREE).getNiceScroll().resize();
		},
		initTreeToolbar : function() {
			var me = this;
			$('.tree-toolbar').on("click", "a.btn", function() {
				if ($(this).hasClass("fa-refresh")) {// 刷新
					me.loadTree();
				} else if ($(this).hasClass("fa-expand")) {// 展开
					me.departmentTree.expandAll(true);
				} else {
					me.departmentTree.expandAll(false);
				}
			});
		},
		blank : function() {
			$("#listFrame").attr("src", '');
		},

		/**
		 * 初始化表单
		 */
		_initForm : function() {
			var me = this, form = $(this.consts.FORM), frm = form.form();
			me.formUrl = new com.lc.form.FormData(form);
			// 触发表单验证
			frm.valid();
			// 处理表单保存
			$(document).on('click', 'a.fa-save', function() {
				var $el = $(this);
				$el.button('loading');
				// office提交
				OfficePlugin.submit();
				me.formUrl.submit(me._showResponse, $el);
			});
		},
		/**
		 * 初始化数据
		 */
		_initData : function() {
			if (!$.isEmpty(frameElement) && !$.isEmpty(frameElement.dialog) && !$.isEmpty(frameElement.dialog.params) && !$.isEmpty(frameElement.dialog.params.data)) {
				var data = frameElement.dialog.params.data;
				this.formUrl.setData("[name^='m:']", data);
			}
			this.formUrl.validate();
		},
		/**
		 * 表单成功返回信息
		 */
		_showResponse : function(responseText) {
			var msg = new com.lc.form.ResultMessage(responseText);
			if (msg.isSuccess()) {
				if (parent.department)
					parent.department.reFresh();
				DialogUtil.alert(msg.getMessage(), function(rtn) {
					if (rtn)
						if (parent.department)
							parent.department.blank();
				});
			} else {
				DialogUtil.error(msg.getMessage());
			}
		}
	};
})();